import { useEffect, useRef, useState, forwardRef, Ref, useImperativeHandle } from 'react';
import { useForm } from '@formily/react';
import QueryContent from './QueryContent';
import { getApiData, setApi, updateApi } from './service';
import { saveApiData } from './utils';
// 接口工厂 接口
export type IModelApi = {
  getValue: () => Promise<{
    value: string;
    sourcetype: 'api';
    primaryKey?: string;
    date: number;
    queryField: [];
  }>;
  getData: () => any
};
function ModelApi(
  props: {
    value?: string;
    type?: 'search' | 'edit';
    isShow: boolean;
    resultKeys?: string[];
    isPrimaryKey?: boolean;
    variableOptions?: string[] | { label: string; value: string }[];
  },
  ref: Ref<IModelApi>,
) {
  const queryContentRef = useRef<{
    getData: () => { searchData: any; editData: any; deleteData: any };
  }>(null);
  const form = useForm();
  const { appInfo } = form as unknown as { appInfo: { appId: string } };
  const [apiData, setApiData] = useState();
  // 用于判断选择的api是否更改
  const [_, setSelectApiData] = useState();
  useEffect(() => {
    if (props.value) {
      getApiData({ appId: appInfo.appId, key: props.value, pageInfo: { index: 1, size: 10 } }).then(
        (res) => {
          setApiData(res);
          setSelectApiData(res?.InterfaceQueryConfig?.SelectConfig?.Key);
        },
      );
    }
  }, [props.value]);

  useImperativeHandle(
    ref,
    () => ({
      getValue: () => {
        return saveApiData({
          queryData: queryContentRef.current?.getData(),
          value: props.value,
          isPrimaryKey: props.isPrimaryKey,
          form
        })
      },
      // 动态列表兼容老版数据源
      getData: () => queryContentRef.current?.getData()
    }),
    [],
  );

  return (
    <QueryContent
      type={['search']}
      modalTitle={'search'}
      queryType={props.type}
      ref={queryContentRef}
      apiData={apiData}
      isShow={props.isShow}
      resultKeys={props.resultKeys}
      isPrimaryKey={props.isPrimaryKey}
      variableOptions={props.variableOptions}
    />
  );
}

export default forwardRef(ModelApi);

function queryFieldToShowFields(apiData: any) {
  const index = apiData?.outConfig?.findIndex(
    (item: { Childrens: string | any[] }) => item.Childrens?.length,
  );
  if (index == -1 || index === undefined) {
    return [];
  }
  return (
    apiData?.outConfig[index]?.Childrens?.map((item: any) => {
      return {
        ...item,
        FieldName: item.Name,
      };
    }) || []
  );
}
